package com.ajavaer.framework.filter;

import com.ajavaer.framework.common.message.Message;
import com.ajavaer.framework.common.tools.JsonTools;
import com.ajavaer.framework.common.tools.StringTools;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class AjaxRequestFilter extends UserFilter {
    Logger log = LoggerFactory.getLogger(AjaxRequestFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (request instanceof HttpServletRequest) {
            if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
                return true;
            }
        }
        Subject subject = SecurityUtils.getSubject();

        if (null != subject) {
            if (subject.isRemembered()) {
                return Boolean.TRUE;
            }
            if (subject.isAuthenticated()) {
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse;
        HttpServletRequest httpRequest;
        httpResponse = WebUtils.toHttp(response);
        httpRequest = WebUtils.toHttp(request);
        String requestedWith = httpRequest.getHeader("X-Requested-With");
        if (StringTools.isNotBlank(requestedWith) && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            WebUtils.saveRequest(request);
            httpResponse.setStatus(HttpStatus.OK.value());
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json; charset=utf-8");
            PrintWriter out = null;
            try {
                out = httpResponse.getWriter();
                out.append(JsonTools.beanToJson(Message.fail(HttpStatus.FORBIDDEN, "登录信息失效,请重新登录")));
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            } finally {
                if (out != null) {
                    out.close();
                }
            }
            return false;
        }
        return super.onAccessDenied(request, response);
    }
}
